package com.oak.broke.utils;

import com.oak.broke.constant.ResponseConstant;
import com.oak.broke.exception.VipException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tdh.sftp.client.Client;
import tdh.sftp.client.SftpClientFactory;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author zhaodong
 * @date 2019/9/5
 */
@Service
@Slf4j
public class FileUtil {

    @Value("${file.server.address}")
    private String fileServerAddr;
    @Value("${file.server.user}")
    private String fileServerUser;
    @Value("${file.server.password}")
    private String fileServerPassword;
    @Value("${file.server.dir}")
    private String dir;
    private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 移动临时文件到正式目录
     *
     * @param tempFilePath 临时文件路径
     * @return
     */
    public String moveFile(String tempFilePath) {
        Client client = SftpClientFactory.buildClient(fileServerAddr, fileServerUser, fileServerPassword);
        String newFilePath = "";
        if (StringUtils.isNumeric(tempFilePath)) {
            return tempFilePath;
        }
        if (!tempFilePath.startsWith("/")) {
            tempFilePath = "/" + tempFilePath;
        }
        if (tempFilePath.startsWith(dir)) {
            newFilePath = tempFilePath;
        } else {
            if (client.existFile(tempFilePath)) {
                String now = LocalDate.now().format(dtf);
                String newFile = dir + now + "/" + UuidUtil.generateUuid() + tempFilePath.substring(tempFilePath.lastIndexOf("."));
                // 若文件移动失败，返回移动错误异常
                if (!client.moveFile(tempFilePath, newFile)) {
                    throw new VipException(ResponseConstant.FILE_SERVER_ERROR);
                }
                newFilePath = newFile;
            } else {
                // 文件不存在，提示错误消息
                throw new VipException(ResponseConstant.FILE_NOT_EXIST);
            }
        }
        return newFilePath;
    }
}
